﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalcEngine
{
    public class CodeCalcEngine : CalcEngine
    {
        private CodeBuilder codeBuilder;
        public CodeCalcEngine(CodeBuilder codeBuilder)
        {
            this.codeBuilder = codeBuilder;
            RegisterFunction("Node", 0, Node);
            RegisterFunction("Quality", 0, Quality);
        }
        static object Node(List<Expression> p)
        {
            return "100";
        }
        static object Quality(List<Expression> p)
        {
            return "100";
        }
        internal override FunctionExpression CreateFunctionExpression(FunctionDefinition fnDef, List<Expression> p)
        {
            FunctionExpression functionExpression = new FunctionExpressionProxy(fnDef, p, codeBuilder);
            return functionExpression;
        }
    }
    class FunctionExpressionProxy : FunctionExpression
    {
        private CodeBuilder codeBuilder;
        public FunctionExpressionProxy(FunctionDefinition function, List<Expression> parms, CodeBuilder codeBuilder)
            : base(function, parms)
        {
            this.codeBuilder = codeBuilder;
            if (base._parms == null)
            {
                base._parms = new List<Expression>();
            }
        }
        public override Expression Optimize()
        {
            if (!codeBuilder.IsWriting)
            {
                codeBuilder.Write(base._fn, base._parms.Cast<ICodeBuilder>().ToList());
            }
            Expression expression = base.Optimize();

            return expression;
        }
        public override string ToCodeString()
        {
            return base._fn.Function.Method.Name.ToLower();
        }
    }
    public interface ICodeBuilder
    {
        string ToCodeString();
    }
}
